package com.example.onlinemarket.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.widget.AppCompatSpinner;
import androidx.appcompat.widget.Toolbar;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.onlinemarket.Application;
import com.example.onlinemarket.R;
import com.example.onlinemarket.adapter.ViewPagerAdapter;
import com.example.onlinemarket.fragment.MainFragment;
import com.example.onlinemarket.fragment.ShoppingCartFragment;
import com.example.onlinemarket.fragment.UserFragment;
import com.example.onlinemarket.graphics.CircleDrawable;
import com.example.onlinemarket.graphics.DrawableClickableEditText;
import com.example.onlinemarket.listener.NavigationItemSelectedListener;
import com.example.onlinemarket.model.Good;
import com.example.onlinemarket.model.User;
import com.example.onlinemarket.util.ActivityUtil;
import com.example.onlinemarket.util.JSONUtil;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.navigation.NavigationView;
import com.google.gson.reflect.TypeToken;
import com.mock.alipay.Callback;
import com.mock.alipay.PasswordKeypad;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;

import de.hdodenhof.circleimageview.CircleImageView;

import static androidx.viewpager2.widget.ViewPager2.SCROLL_STATE_IDLE;
import static com.example.onlinemarket.Application.dismissProgressDialog;
import static com.example.onlinemarket.Application.getBitmap;
import static com.example.onlinemarket.Application.loginUser;
import static com.example.onlinemarket.Application.setBigUserImg;
import static com.example.onlinemarket.activity.ImgUpdateActivity.isImgUpdated;
import static com.example.onlinemarket.util.HttpUtil.sendHttpRequest;

public class MainActivity extends BaseActivity {

    private DrawerLayout drawer;
    private NavigationView navigationView;
    private BottomNavigationView bottomNavigationView;
    private ViewPager2 viewPager;
    private CircleImageView drawer_userImgIv;
    private TextView drawer_userNameTv;

    private LinearLayout searchLayout;
    private AppCompatSpinner searchSelectSp;
    private AppCompatSpinner searchSpeciesSp;
    private DrawableClickableEditText searchContentEt;
    private NavigationItemSelectedListener navListener;
    private int searchSelectSpPos = 0;
    private int searchSpeciesSpPos = 0;
    private int pageSize = 5;//分页查询的单页大小
    private String lastSearchContent;//记录上一次的查询内容
    private String lastSearchSpecies;// TODO: 2021/6/1
    private List<User> userList;
    private List<Good> goodList;

    protected MainFragment mainFragment;
    private ShoppingCartFragment shoppingCartFragment;
    protected UserFragment userInfoFragment;
    protected int pageNum = 0;
    private long firstClick;

    private PasswordKeypad keypad;
    private AtomicBoolean isConfirm = new AtomicBoolean(false);
    private AtomicReference<String> pwd = new AtomicReference<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置布局
        setContentView(R.layout.activity_main);
        //初始化组件
        initWidgets();
        //为组件设置监听器
        setWidgetsListener();
        //初始化Fragment
        initFragments();
        dismissProgressDialog();

        //陈雪
        new Thread(() -> {
            String responseData = sendHttpRequest("/search/goodAll", "GET",null);
            if(responseData!=null&&!responseData.isEmpty()){
                List<Good> goods = JSONUtil.fromJsons(responseData, new TypeToken<List<Good>>() {}.getType());
                if(goods.size()>0)
                    mainFragment.updateGoodData(goods, true);
                else
                    showBlankPage();
            }
        }).start();

    }

    //初始化Fragment
    private void initFragments(){
        mainFragment = new MainFragment();
        mainFragment.setOnLoadMoreListener(this::search);
        shoppingCartFragment = new ShoppingCartFragment();
        userInfoFragment = new UserFragment();
        List<Fragment> fragmentList = new ArrayList<>();
        fragmentList.add(mainFragment);
        fragmentList.add(shoppingCartFragment);
        fragmentList.add(userInfoFragment);
        viewPager.setAdapter(new ViewPagerAdapter(this, fragmentList));
        initMainFragment();
        if(loginUser.getPayPassword()==null){
            keypad = getKeyPad();
            keypad.show(getSupportFragmentManager(), "PasswordKeypad");
        }
    }

    private PasswordKeypad getKeyPad(){
        PasswordKeypad passwordKeypad = new PasswordKeypad("设置交易密码");
        passwordKeypad.setPasswordCount(6);
        passwordKeypad.setCancelable(false);
        passwordKeypad.setCallback(new Callback() {
            @Override
            public void onForgetPassword() {
                Toast.makeText(MainActivity.this, "忘记密码",Toast.LENGTH_LONG).show();
            }
            @Override
            public void onInputCompleted(CharSequence password) {
                new Handler().postDelayed(() -> {
                    if(!isConfirm.get()){
                        pwd.set(password.toString());
                        Toast.makeText(MainActivity.this, "请再次确认密码", Toast.LENGTH_SHORT).show();
                        resetKeyPad(false);
                    }else{
                        if(password.toString().equals(pwd.get())){
                            updatePayPassword();
                        }else {
                            Toast.makeText(MainActivity.this, "输入错误", Toast.LENGTH_SHORT).show();
                            isConfirm.set(false);
                            keypad.setPasswordState(false);
                        }

                    }
                },1000);
            }

            @Override
            public void onPasswordCorrectly() {
                passwordKeypad.dismiss();
            }

            @Override
            public void onCancel() {
                Toast.makeText(MainActivity.this, "必须设置支付密码", Toast.LENGTH_SHORT).show();
                resetKeyPad(true);
            }
        });
        return passwordKeypad;
    }

    private void updatePayPassword(){
        new Thread(() -> {
            Map<String, String> map = new HashMap<>();
            map.put("userId", String.valueOf(loginUser.getUserId()));
            map.put("payPassword", pwd.get());
            String response = sendHttpRequest("/updatePayPassword", "POST", map);
            System.out.println("设置密码反馈"+response);
            if(response!=null&&!response.isEmpty()){
                runOnUiThread(() -> {
                    if(response.equals("true")){
                        Toast.makeText(MainActivity.this, "交易密码设置完成", Toast.LENGTH_SHORT).show();
                        loginUser.setPayPassword(pwd.get());
                        keypad.setPasswordState(true);
                    }else{
                        Toast.makeText(MainActivity.this, "首页交易密码设置失败", Toast.LENGTH_SHORT).show();
                        keypad.dismiss();
                    }
                });
            }
        }).start();
    }

    private void resetKeyPad(boolean flag){
        keypad.dismiss();
        isConfirm.set(!flag);
        keypad = getKeyPad();
        keypad.show(getSupportFragmentManager(), "PasswordKeypad");
    }

    //初始化主界面
    private void initMainFragment(){
        viewPager.setCurrentItem(0);
//        searchLayout.setVisibility(View.VISIBLE);
        userList = new ArrayList<>();
        goodList = new ArrayList<>();
    }

    public interface OnLoadMoreListener{
        void onLoadMore();
    }

    protected void search() {
        new Thread(() -> {
            String searchContent = Objects.requireNonNull(searchContentEt.getText()).toString().trim();
            if(!searchContent.isEmpty()){
                Map<String, String> map = new HashMap<>();
                map.put("searchContent", searchContent);
                map.put("pageSize", String.valueOf(pageSize));//设置分页查询大小
                String searchSelect = getResources().getStringArray
                        (R.array.search_select)[searchSelectSpPos];
                boolean isNewSearch = !searchContent.equals(lastSearchContent);
                if(searchSelect.equals("商品")) {
                    String searchSpecies = getResources().getStringArray
                            (R.array.search_species)[searchSpeciesSpPos];
                    map.put("searchSpecies", searchSpecies);
                    boolean isNewSearchSpecies = !searchSpecies.equals(lastSearchSpecies);
                    if(isNewSearchSpecies)
                        lastSearchSpecies = searchSpecies;
                    isNewSearch = isNewSearch||isNewSearchSpecies;
                }
                if(isNewSearch){
                    goodList.clear();
                    userList.clear();
                    lastSearchContent = searchContent;
                }
                if(searchSelect.equals("商品"))
                    searchGood(map, isNewSearch);//搜索商品
                else
                    searchShop(map, isNewSearch);//搜索商铺
            }else
                runOnUiThread(this::showBlankPage);
        }).start();
    }

    //显示无数据空白页
    private void showBlankPage(){
        goodList.clear();
        userList.clear();
        lastSearchContent = "";
        lastSearchSpecies = "";
        mainFragment.showBlankPage();
    }

    //搜索商品
    private void searchGood(Map<String, String> map, boolean isFullyUpdate) {
        new Thread(() -> {
            map.put("recorded", String.valueOf(goodList.size()));
            String responseData = sendHttpRequest("/search/good", "POST", map);
            if(responseData!=null&&!responseData.isEmpty()){
                List<Good> goods = JSONUtil.fromJsons(responseData, new TypeToken<List<Good>>() {}.getType());
                if(goods.size()>0)
                    mainFragment.updateGoodData(goods, isFullyUpdate);
                else
                    showBlankPage();
            }
        }).start();
    }

    //搜索商铺
    private void searchShop(Map<String, String> map, boolean isFullyUpdate){
        new Thread(() -> {
            map.put("recorded", String.valueOf(userList.size()));
            String responseData = sendHttpRequest("/search/shop", "POST", map);
            if(responseData!=null&&!responseData.isEmpty()){
                List<User> users = JSONUtil.fromJsons(responseData, new TypeToken<List<User>>() {}.getType());
                for(User user : users){
                    boolean isExists = false;
                    for(User item:userList){
                        isExists = isExists || item.getUserId().equals(user.getUserId());
                    }
                    if(!isExists){
                        user.getUserImg();
                        userList.add(user);
                    }
                }
                mainFragment.updateShopData(userList,true);
            }
        }).start();
    }

    //隐藏软键盘
    private void hideKeyboard() {
        searchContentEt.clearFocus();
        View decorView = getWindow().peekDecorView();
        if (decorView != null) {
            InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.hideSoftInputFromWindow(decorView.getWindowToken(), 0);
        }
    }


    //初始化组件
    @SuppressLint("WrongConstant")
    private void initWidgets() {
        drawer = findViewById(R.id.drawer_layout);
        drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);//禁止手势滑动打开侧滑菜单
        searchLayout = findViewById(R.id.layout_app_bar_search);
        searchSelectSp = findViewById(R.id.sp_app_bar_search_select);
        searchSpeciesSp = findViewById(R.id.sp_app_bar_search_species);
        searchContentEt = findViewById(R.id.et_app_bar_search_content);
        viewPager = findViewById(R.id.view_pager);
        navigationView = findViewById(R.id.navigation_view);
        bottomNavigationView = findViewById(R.id.bottom_nav_view);
        drawer_userImgIv = navigationView.getHeaderView(0).findViewById(R.id.iv_drawer_img);
        drawer_userNameTv = navigationView.getHeaderView(0).findViewById(R.id.tv_drawer_user_name);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();//获取ActionBar（实际由Toolbar实现）
        if(actionBar!=null){
            //启用导航键，即HomeAsUp按钮y
            actionBar.setDisplayHomeAsUpEnabled(true);
            //将HomeAsUp按钮设置为导航键并指定图标
//            new Thread(() -> {
//                if (loginUser!=null){
//                    Drawable drawable = new CircleDrawable(getBitmap(MainActivity.this, loginUser.getLocalPath(), 150));
//                    runOnUiThread(() -> actionBar.setHomeAsUpIndicator(drawable));
//                }
//
//            }).start();
        }
        setBigUserImg(this, drawer_userImgIv);
        drawer_userNameTv.setText(loginUser.getUserName());
    }

    //为组件设置监听器
    @SuppressLint("WrongConstant")
    private void setWidgetsListener(){
        //创建菜单监听器
        navListener = new NavigationItemSelectedListener(searchLayout,
                drawer, navigationView, bottomNavigationView, viewPager);
        //展示主页，并禁用主页按钮
        navListener.showIndex();
        bottomNavigationView.setOnNavigationItemSelectedListener(navListener);
        navigationView.setNavigationItemSelectedListener(navListener);
        //点击侧滑菜单的用户头像，打开用户信息页面
        drawer_userImgIv.setOnClickListener(v -> navListener.showUserInfo());
        searchSpeciesSp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                searchSpeciesSpPos = position;
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });
        searchSelectSp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                searchSelectSpPos = position;
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });
        searchContentEt.setOnEditorActionListener((v, actionId, event) -> {
            if((actionId == EditorInfo.IME_ACTION_SEARCH)
            ||(event.getKeyCode() == KeyEvent.KEYCODE_ENTER)){
                hideKeyboard();//隐藏软键盘
                search();
            }
            return true;
        });
        searchContentEt.setOnDrawableEndListener(view -> {
            hideKeyboard();//隐藏软键盘
            search();
        });
        ViewPager2.OnPageChangeCallback onPageChangeCallback = new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageScrollStateChanged(int state) {
                super.onPageScrollStateChanged(state);
                if (state == SCROLL_STATE_IDLE){
                    int currentItem = viewPager.getCurrentItem();// TODO: 2021/6/1
                    if(currentItem!=pageNum){
                        pageNum = currentItem;
                        switch (currentItem){
                            case 0:
                                navListener.showIndex();
                                break;
                            case 1:
                                navListener.showShoppingCart();
                                break;
                            case 2:
                                navListener.showUserInfo();
                                break;
                            default:
                                break;
                        }
                    }
                }
            }
        };
        viewPager.registerOnPageChangeCallback(onPageChangeCallback);
    }

    @SuppressLint("WrongConstant")
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();
        if(id == android.R.id.home)
            drawer.openDrawer(Gravity.START);
        return super.onOptionsItemSelected(item);
    }

    //密码更改后要求用户重新登录
    public void passwordChanged(){
        SharedPreferences.Editor editor = getSharedPreferences("login", MODE_PRIVATE).edit();
        editor.putString("password", "");
        editor.apply();
        Application.isLogout = true;
        Toast.makeText(this, "密码已经更改，请重新登录", Toast.LENGTH_SHORT).show();
        finish();
    }

    /**
     * 连按两次Back键退出程序
     * @param keyCode 按键对应按键值，用于判断所按按键
     * @param event 按键事件
     * @return 若所按按键为Back键则返回true，否则返回false
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onAppExit();
            return true;
        }
        return false;
    }

    //连按两次Back键退出程序
    public void onAppExit() {
        if (System.currentTimeMillis() - this.firstClick > 2000L) {
            this.firstClick = System.currentTimeMillis();
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_LONG).show();
            return;
        }
        ActivityUtil.removeAll();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        if(requestCode==0&&isImgUpdated)//若头像更新则刷新头像
            refreshUserImg();
        super.onActivityResult(requestCode, resultCode, data);
    }

    //刷新用户头像
    protected void refreshUserImg(){
        userInfoFragment.setUserImg();
        setBigUserImg(this, drawer_userImgIv);
        ActionBar actionBar = getSupportActionBar();
        if(actionBar!=null){
            //将HomeAsUp按钮设置为导航键并指定图标
            new Thread(() -> { ;
                Drawable drawable = new CircleDrawable(getBitmap(MainActivity.this, loginUser.getLocalPath(), 150));
                runOnUiThread(() -> actionBar.setHomeAsUpIndicator(drawable));
            }).start();
        }
        isImgUpdated = false;
    }
}